package com.epam.newsmanagement.database.dao.hibernate;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;

import com.epam.newsmanagement.database.dao.INewsDAO;
import com.epam.newsmanagement.database.dao.exception.DAOException;
import com.epam.newsmanagement.model.News;


public final class HibernateNewsDAO implements INewsDAO{
	private final static String HQL_READ_ALL = "read_all";
	private final static String HQL_FETCH_BY_ID = "fetch_by_id";
	private final static String HQL_DELETE = "delete";
	private final static String HQL_PARAMETER_ID = "ID";
	private final static String HQL_PARAMETER_SELECTED_NEWS = "selectedNews";
	private SessionFactory sessionFactory;

	@Override
	public void save(News news) throws DAOException {
		Session session = sessionFactory.getCurrentSession();
		session.beginTransaction();
		session.saveOrUpdate(news);
		session.getTransaction().commit();
	}
	
	@SuppressWarnings("unchecked")
	@Override
	public List<News> getList() throws DAOException {
		Session session = sessionFactory.getCurrentSession();
		session.beginTransaction();
		Query query = session.getNamedQuery(HQL_READ_ALL);
		List<News> newsList = query.list();
		session.beginTransaction().commit();
		return newsList;
	}

	@Override
	public void remove(Integer[] selectedNews) throws DAOException {
		Session session = sessionFactory.getCurrentSession();
		session.beginTransaction();
		Query query = session.getNamedQuery(HQL_DELETE);
		query.setParameterList(HQL_PARAMETER_SELECTED_NEWS, selectedNews);
		query.executeUpdate();
		session.getTransaction().commit();
		
	}

	@Override
	public News fetchById(int id) throws DAOException {
		Session session = sessionFactory.getCurrentSession();
		session.beginTransaction();
		Query query = session.getNamedQuery(HQL_FETCH_BY_ID);
		query.setParameter(HQL_PARAMETER_ID, id);
		News news = (News)query.uniqueResult();
		session.getTransaction().commit();
		return news;
	}

	public SessionFactory getSessionFactory() {
		return sessionFactory;
	}

	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}

}
